import {ref,inject} from 'vue-demi'
import RouterLink from './RouterLink.vue'
import RouterView from './RouterView.vue'

const ROUTER_KEY = '__router__'

// 创造实例函数
function createRouter(options){
    return new Router(options)
}

// 返回实例函数
function useRouter(){
    return inject(ROUTER_KEY)
}

// 创建history对象
function createWebHashHistory(){
    function bindEvents(fn){
        window.addEventListener('hashchange',fn)
    }
    return {
        bindEvents,
        url:window.location.hash.slice(1) || '/'
    }
}

// Router类{options:{history,routes,current}}
class Router{
    constructor(options){
        this.history = options.history
        this.routes = options.routes
        // 包裹一个响应式对象
        this.current = ref(this.history.url)
        this.history.bindEvents(()=>{
            this.current.value = window.location.hash.slice(1)
        })
    }
    install(app){
        alert(1)
        app.provide(ROUTER_KEY,this)
        app.component("router-link",RouterLink)
        app.component("router-view",RouterView)
    }
}

export {createRouter,createWebHashHistory,useRouter}